//
//  UITextField+SLSDK.m
//  SLSDK
//
//  Created by SongLian on 16/8/7.
//  Copyright © 2016年 SongLian. All rights reserved.
//

#import "UITextField+SLSDK.h"
#import "NSObject+SLSDK.h"

static NSString * const key_sl_wordLimit = @"key_sl_wordLimit";
static NSString * const key_sl_decimalLimit = @"key_sl_decimalLimit";

@implementation UITextField (SLSDK)

- (void)setSl_wordLimit:(NSInteger)sl_wordLimit {
    [self sl_objc_setAssociatedInteger:sl_wordLimit forKey:key_sl_wordLimit];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sl_limitTextFieldWord) name:UITextFieldTextDidChangeNotification object:nil];
}

- (NSInteger)sl_wordLimit {
    return [self sl_objc_getAssociatedIntegerForKey:key_sl_wordLimit];
}

- (void)setSl_decimalLimit:(NSInteger)sl_decimalLimit {
    [self sl_objc_setAssociatedInteger:sl_decimalLimit forKey:key_sl_decimalLimit];
    if (self.keyboardType == UIKeyboardTypeDecimalPad)
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sl_limitTextFieldDecimal) name:UITextFieldTextDidChangeNotification object:nil];
}

- (NSInteger)sl_decimalLimit {
    return [self sl_objc_getAssociatedIntegerForKey:key_sl_decimalLimit];
}

- (void)sl_limitTextFieldWord {
    if ((!self.markedTextRange) && (self.text.length > self.sl_wordLimit))
        self.text = [self.text substringToIndex:self.sl_wordLimit];
}

- (void)sl_limitTextFieldDecimal {
    NSArray *array = [self.text componentsSeparatedByString:SLString_Point];
    if (array.count > 2 || (array.count == 2 && [array.lastObject length] > 2))
        self.text = [self.text sl_substringWithLastCharacter];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
